package com.my.webflux.controller;

import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebSession;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;

/**
 * @author zhupanlin
 * @version 1.0
 * @description: TODO
 * @date 2024/2/18 12:13
 */

@RestController
public class HelloController {
    
    @GetMapping("/entity")
    public ResponseEntity<String> entity(){
        
        return ResponseEntity.status(305)
                .header("aaa", "bbb")
                .contentType(MediaType.APPLICATION_JSON)
                .body("aaaa");
        
    }
    
    @GetMapping("/error")
    public Mono<String> error(){
        return Mono.just(0)
                .map(i -> 10 / i)
                .map(i -> "哈哈-" + i);
    }
    
    @GetMapping("/hello")
    public String hello(@RequestParam(value = "key", required = false, defaultValue = "哈哈") String key,
                        ServerWebExchange exchange,
                        WebSession webSession,
                        HttpMethod httpMethod,
                        HttpEntity<String> entity){
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        ApplicationContext applicationContext = exchange.getApplicationContext();
        Object aaa = webSession.getAttribute("aaa");
        Object put = webSession.getAttributes().put("bbb", "ccc");
        System.out.println("httpMethod.name() = " + httpMethod.name());
        System.out.println("entity = " + entity);
        return "Hello World !! key : " + key ;
    }
    
    @GetMapping("/haha")
    public Mono<String> haha(){
        
        return Mono.just("哈哈");
        
    }
    
    
    @GetMapping("/hehe")
    public Flux<String> hehe(){
        return Flux.just("hehe1", "hehe2");
    }
    
    @GetMapping(value = "/sse", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> sse(){
        
        return Flux.range(1, 10)
                .map(i -> "ha-" + i)
                .delayElements(Duration.ofMillis(500));
        
    }
}
